import gradio as gr
import base64
import os
import cv2
import numpy as np
from processing import ProcessingModel
import merge  # 导入merge模块

# ======================
# 全局常量定义
# ======================
STATIC_DIR = os.path.join(os.path.dirname(__file__), "static")
SIMHEI_FONT_PATH = os.path.join(STATIC_DIR, "SimHei.ttf")

# 加载GIF资源
with open(os.path.join(STATIC_DIR, "xiaoxin.gif"), "rb") as f:
    GIF_BASE64 = base64.b64encode(f.read()).decode("utf-8")

# 修改CSS部分
CSS = """
.center-btn-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
}

.btn-class {
    min-width: 200px;
    max-width: 300px;
    width: auto !important;
    flex: none !important;
}

.audio-controls {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10px;
    width: 100%;
}

/* 作用在外层容器，允许内容根据需要扩展 */
.audio-status {
    width: auto !important;
    min-width: 800px !important;    /* 你想要的最小宽度 */
    max-width: 90vw !important;     /* 响应式上限，避免超出视口 */
    box-sizing: border-box;
}

/* 作用在实际的输入元素（textarea），确保内部元素跟随外层 */
.audio-status textarea,
.audio-status .gradio-textbox,
.audio-status .input_text {       /* 根据 Gradio 版本不同，选择合适的选择器 */
    width: 100% !important;
    min-width: 800px !important;
    max-width: 90vw !important;
    box-sizing: border-box;
    white-space: pre-wrap;
    word-wrap: break-word;
    overflow-wrap: break-word;
    resize: vertical;
    min-height: 100px;
}

"""

# ======================
# 全局状态
# ======================
class AppState:
    def __init__(self):
        self.processing_model = ProcessingModel()
        self.camera_active = False
        self.cap = None
        self.use_chinese = False

app_state = AppState()

# ======================
# Gradio界面回调函数
# ======================

def on_model_load(model_name):
    """模型加载回调函数"""
    model, info = app_state.processing_model.load_model(model_name)
    
    if model:
        info_md = "## 🎯 模型加载成功！\n"
        for key, value in info.items():
            info_md += f"- **{key}**: `{value}`  \n"
        return info_md
    else:
        return info

def on_language_change(language):
    """语言切换回调函数"""
    app_state.use_chinese = (language == "中文")
    visible = app_state.use_chinese
    return gr.update(visible=visible), gr.update(visible=visible)

def on_image_predict(input_image, label_mapping_file):
    """图像预测回调函数"""
    label_mapping, _ = app_state.processing_model.read_label_mapping(label_mapping_file.name if label_mapping_file else None)
    return app_state.processing_model.predict_image(input_image, label_mapping, app_state.use_chinese)

def on_video_predict(input_video, label_mapping_file):
    """视频预测回调函数"""
    label_mapping, _ = app_state.processing_model.read_label_mapping(label_mapping_file.name if label_mapping_file else None)
    return app_state.processing_model.predict_video(input_video.name, label_mapping, app_state.use_chinese)

def generate_video_frames(video_path, label_mapping_file, language):
    """视频帧生成器：逐帧读取并返回检测后的图像帧"""
    use_chinese_flag = (language == "中文")
    label_mapping, _ = app_state.processing_model.read_label_mapping(label_mapping_file.name if label_mapping_file else None)
    
    cap = cv2.VideoCapture(video_path)
    if not cap.isOpened():
        raise ValueError("无法打开视频文件")

    try:
        while cap.isOpened():
            ret, frame = cap.read()
            if not ret:
                break
            processed = app_state.processing_model.predict_image(frame, label_mapping, use_chinese_flag)
            yield processed
    finally:
        cap.release()

# 修改摄像头控制函数
def on_camera_start():
    """启动摄像头回调函数"""
    if app_state.camera_active:
        return "⚠️ 摄像头已经在运行中..."
    
    app_state.cap = cv2.VideoCapture(0)
    if not app_state.cap.isOpened():
        return "❌ 无法打开摄像头"
    
    app_state.camera_active = True
    return "🟢 摄像头已启动"

def on_camera_stop():
    """停止摄像头回调函数"""
    app_state.camera_active = False
    if app_state.cap and app_state.cap.isOpened():
        app_state.cap.release()
    return "🛑 摄像头已关闭"

def generate_camera_frames():
    """生成摄像头帧"""
    while app_state.camera_active:
        ret, frame = app_state.cap.read()
        if not ret:
            break
        yield frame

def generate_camera_frames_with_detection():
    """
    生成带目标检测的摄像头帧
    """
    while app_state.camera_active:
        ret, frame = app_state.cap.read()
        if not ret:
            break
        
        try:
            # 对帧进行目标检测
            label_mapping, _ = app_state.processing_model.read_label_mapping(None)  # 使用空标签映射
            processed_frame = app_state.processing_model.predict_image(frame, label_mapping, app_state.use_chinese)
            yield processed_frame
        except Exception as e:
            print(f"摄像头检测出错: {e}")
            # 出错时返回原始帧
            yield cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

def on_person_selection_change(label_mapping_file):
    """
    当标签映射文件更改时，更新人物选择列表
    """
    persons = app_state.processing_model.get_person_classes(label_mapping_file.name if label_mapping_file else None)
    return gr.update(choices=persons, value=[])

def on_extract_persons(video_input, selected_persons, label_mapping_file):
    """
    提取选定人物帧并生成视频
    """
    if not video_input:
        return None
    
    if not selected_persons:
        return None
    
    try:
        return app_state.processing_model.extract_person_frames(video_input.name, selected_persons, label_mapping_file.name if label_mapping_file else None)
    except Exception as e:
        print(f"处理出错: {e}")
        return None

def on_restore_audio(original_video, extracted_video, timestamps_csv):
    """
    恢复视频音频的回调函数
    """
    if not original_video or not extracted_video or not timestamps_csv:
        return None, "请上传所有必需的文件：原始视频、提取视频和时间戳CSV文件"
    
    try:
        # 获取提取视频的帧率
        frame_rate_of_extracted_video = merge.get_video_frame_rate(extracted_video.name)
        
        # 临时音频文件路径
        temp_restored_audio = "temp_restored_audio.wav"
        
        # 提取并合并音频
        merge.extract_audio_segments(
            original_video.name, 
            timestamps_csv.name, 
            temp_restored_audio, 
            frame_rate_of_extracted_video
        )
        
        # 临时输出视频路径
        import tempfile
        with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as temp_file:
            output_video_path = temp_file.name
        
        # 合成最终视频
        merge.merge_audio_video(
            extracted_video.name, 
            temp_restored_audio, 
            output_video_path
        )
        
        # 清理临时音频文件
        if os.path.exists(temp_restored_audio):
            os.remove(temp_restored_audio)
            
        return output_video_path, f"音频恢复成功！输出文件路径: {output_video_path}"
        
    except Exception as e:
        return None, f"处理过程中发生错误: {str(e)}"

# ======================
# Gradio界面构建
# ======================

def create_interface():
    """创建Gradio界面"""
    with gr.Blocks(theme=gr.themes.Soft(), css=CSS) as demo:
        with gr.Tab("目标检测"):    
            # 侧边栏
            with gr.Sidebar(position="left", open=False):
                gr.Markdown(f"""
                <h1 style="display: inline-flex; align-items: center; gap: 8px;">
                    <img src='data:image/gif;base64,{GIF_BASE64}' width='64' style='vertical-align: middle;' />
                    <span>目标检测系统</span>
                </h1>
                """)
                
                # 模型选择与加载
                model_select = gr.Dropdown(
                    choices=app_state.processing_model.get_available_models(),
                    label="选择检测模型",
                    value=app_state.processing_model.get_available_models()[0]
                )
                model_load_btn = gr.Button("加载模型", variant="primary")
                model_info = gr.Markdown("""
                <div style="display: flex; justify-content: center;">
                    <h1 style="font-size: 1.4em;">请加载模型😊</h1>
                </div>
                """)
                
                # 语言选择
                gr.Markdown("---\n### 标签设置")
                language = gr.Radio(
                    choices=["中文", "English"],
                    label="标签语言",
                    value="English"
                )
                label_mapping_file = gr.File(visible=False, label="标签映射文件")
                label_mapping_display = gr.Textbox(visible=False, label="当前映射")
                
                # 组件交互
                model_load_btn.click(on_model_load, inputs=model_select, outputs=model_info)
                language.change(on_language_change, inputs=language, outputs=[label_mapping_file, label_mapping_display])
                label_mapping_file.change(
                    fn=lambda x: app_state.processing_model.read_label_mapping(x.name if x else None)[1], 
                    inputs=label_mapping_file, 
                    outputs=label_mapping_display
                )
            
            # 图像检测标签页
            with gr.Tab("图像检测"):
                gr.Markdown("""
                <div style="text-align: center;">
                    <h1 style="font-size: 2em;">基于 YOLO 的目标检测</h1>
                    <p>上传图片进行目标检测，支持中英文标签</p>
                </div>
                """)
                with gr.Row():
                    image_input = gr.Image(height=640, label="输入图片", type="filepath")
                    image_output = gr.Image(height=600, label="检测结果",)
                
                with gr.Row(elem_classes=["center-btn-container"]):
                    predict_btn = gr.Button("开始检测", variant="primary", elem_classes=["btn-class"])
                    predict_btn.click(on_image_predict, inputs=[image_input, label_mapping_file], outputs = image_output)
            
            # 视频检测标签页
            with gr.Tab("视频检测"):
                gr.Markdown("""
                <div style="text-align: center;">
                    <h1 style="font-size: 2em;">视频目标检测</h1>
                    <p>上传视频进行目标检测，支持中英文标签</p>
                </div>
                """)
                video_input = gr.File(label="上传视频", file_types=["video"])
                with gr.Row():  
                    video_output = gr.Video(height=640, label="检测结果")
                with gr.Row(elem_classes=["center-btn-container"]): 
                    predict_video_btn = gr.Button("开始生成", variant="primary", elem_classes=["btn-class"])
                    predict_video_btn.click(on_video_predict, inputs=[video_input, label_mapping_file], outputs=video_output)
            
            # 摄像头标签页
            with gr.Tab("实时摄像头"):
                gr.Markdown("""
                <div style="text-align: center;">
                    <h1 style="font-size: 2em;">🎥 实时摄像头检测</h1>
                    <p>使用摄像头进行实时目标检测</p>
                </div>
                """)
                camera_output = gr.Image(height=600, label="摄像头画面", streaming=True)
                
                with gr.Row():
                    start_btn = gr.Button("🟢 启动摄像头", variant="secondary")
                    stop_btn = gr.Button("🛑 停止摄像头", variant="secondary")
                    detect_btn = gr.Button("🔍 开始检测", variant="secondary")
                
                camera_status = gr.Textbox(label="摄像头状态", value="状态: 未启动")
                
                start_btn.click(on_camera_start, outputs=camera_status)
                stop_btn.click(on_camera_stop, outputs=camera_status)
                detect_btn.click(generate_camera_frames, outputs=camera_output)
            
            # 截取主要人物标签页
            with gr.Tab("截取主要人物"):
                gr.Markdown("""
                <div style="text-align: center;">
                    <h1 style="font-size: 2em;">截取主要人物</h1>
                    <p>从视频中提取包含选定人物的帧并生成新视频</p>
                </div>
                """)
                
                with gr.Row():
                    with gr.Column():
                        person_video_input = gr.File(label="上传视频", file_types=["video"])
                        person_label_mapping_file = gr.File(label="标签映射文件（可选）")
                        person_choices = gr.CheckboxGroup(
                            choices=[], 
                            label="选择要提取的人物",
                            info="请选择一个或多个要从视频中提取的人物类别"
                        )
                        extract_btn = gr.Button("开始提取", variant="primary")
                    
                    with gr.Column():
                        person_video_output = gr.Video(height=640, label="提取结果")
                
                # 更新人物选择列表
                person_label_mapping_file.change(
                    on_person_selection_change,
                    inputs=[person_label_mapping_file],
                    outputs=[person_choices]
                )
                
                # 提取人物按钮点击事件
                extract_btn.click(
                    on_extract_persons,
                    inputs=[person_video_input, person_choices, person_label_mapping_file],
                    outputs=[person_video_output]
                )

        # 在声音提取标签页中修改按钮和状态文本框部分
        with gr.Tab("声音提取"):
            gr.Markdown("""
            <div style="text-align: center;">
                <h1 style="font-size: 2em;">🎵 音频恢复</h1>
                <p>将原始视频的音频恢复到提取后的视频中</p>
            </div>
            """)
            
            with gr.Row():
                with gr.Column():
                    gr.Markdown("### 📥 输入文件")
                    original_video = gr.File(label="原始视频文件", file_types=["video"])
                    extracted_video = gr.File(label="提取后的视频文件", file_types=["video"])
                    timestamps_csv = gr.File(label="时间戳CSV文件", file_types=[".csv"])
                    
                with gr.Column():
                    gr.Markdown("### 📤 输出结果")
                    restored_video = gr.Video(label="音频恢复后的视频")
            
            # 居中显示按钮和状态文本框
            with gr.Row(elem_classes=["audio-controls"]):
                restore_btn = gr.Button("开始恢复音频", variant="primary", elem_classes=["btn-class"])
                status_text = gr.Textbox(label="处理状态", interactive=False, elem_classes=["audio-status"])
            
            restore_btn.click(
                on_restore_audio,
                inputs=[original_video, extracted_video, timestamps_csv],
                outputs=[restored_video, status_text]
            )

        # 帮助标签页
        with gr.Tab("帮助说明"):
            gr.HTML("""
            <div style="text-align: center; margin-bottom: 20px;">
                <h1 style="color: #2C3E50; font-size: 3em; margin-bottom: 10px;">📘 YOLO 目标检测系统</h1>
                <p style="font-size: 1.5em; color: #7F8C8D;">基于深度学习的智能目标检测解决方案</p>
            </div>
            
            <div style="background: linear-gradient(135deg, #E8F4FD 0%, #E8F8F5 100%); color: #2C3E50; padding: 25px; border-radius: 15px; margin-bottom: 25px; box-shadow: 0 6px 12px rgba(0,0,0,0.05);">
                <h2 style="margin-top: 0; text-align: center; font-size: 2em; color: #3498DB;">✨ 系统特色功能</h2>
                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; margin-top: 20px;">
                    <div style="background: rgba(255, 255, 255, 0.7); padding: 20px; border-radius: 12px; box-shadow: 0 4px 8px rgba(0,0,0,0.08);">
                        <p style="font-size: 1.3em; margin: 0; display: flex; align-items: center;">
                            <span style="font-size: 1.8em; margin-right: 10px;">🚀</span>
                            <span><strong>实时目标检测</strong> - 支持摄像头实时检测</span>
                        </p>
                    </div>
                    <div style="background: rgba(255, 255, 255, 0.7); padding: 20px; border-radius: 12px; box-shadow: 0 4px 8px rgba(0,0,0,0.08);">
                        <p style="font-size: 1.3em; margin: 0; display: flex; align-items: center;">
                            <span style="font-size: 1.8em; margin-right: 10px;">📸</span>
                            <span><strong>图像检测</strong> - 支持静态图片目标识别</span>
                        </p>
                    </div>
                    <div style="background: rgba(255, 255, 255, 0.7); padding: 20px; border-radius: 12px; box-shadow: 0 4px 8px rgba(0,0,0,0.08);">
                        <p style="font-size: 1.3em; margin: 0; display: flex; align-items: center;">
                            <span style="font-size: 1.8em; margin-right: 10px;">🎬</span>
                            <span><strong>视频检测</strong> - 支持视频文件批量处理</span>
                        </p>
                    </div>
                    <div style="background: rgba(255, 255, 255, 0.7); padding: 20px; border-radius: 12px; box-shadow: 0 4px 8px rgba(0,0,0,0.08);">
                        <p style="font-size: 1.3em; margin: 0; display: flex; align-items: center;">
                            <span style="font-size: 1.8em; margin-right: 10px;">👤</span>
                            <span><strong>人物提取</strong> - 从视频中提取特定人物帧</span>
                        </p>
                    </div>
                    <div style="background: rgba(255, 255, 255, 0.7); padding: 20px; border-radius: 12px; box-shadow: 0 4px 8px rgba(0,0,0,0.08);">
                        <p style="font-size: 1.3em; margin: 0; display: flex; align-items: center;">
                            <span style="font-size: 1.8em; margin-right: 10px;">🔊</span>
                            <span><strong>音频恢复</strong> - 为提取的视频恢复原始音频</span>
                        </p>
                    </div>
                    <div style="background: rgba(255, 255, 255, 0.7); padding: 20px; border-radius: 12px; box-shadow: 0 4px 8px rgba(0,0,0,0.08);">
                        <p style="font-size: 1.3em; margin: 0; display: flex; align-items: center;">
                            <span style="font-size: 1.8em; margin-right: 10px;">🌍</span>
                            <span><strong>多语言支持</strong> - 中英文标签自由切换</span>
                        </p>
                    </div>
                </div>
            </div>
            
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(400px, 1fr)); gap: 30px; margin-bottom: 30px;">
                <div style="background: #F8F9FA; padding: 25px; border-radius: 15px; box-shadow: 0 6px 12px rgba(0,0,0,0.05);">
                    <h2 style="color: #3498DB; border-bottom: 3px solid #3498DB; padding-bottom: 15px; font-size: 1.8em;">🧭 使用指南</h2>
                    
                    <div style="margin-bottom: 25px;">
                        <h3 style="color: #2C3E50; font-size: 1.4em;">
                            <span style="display: inline-block; background: #3498DB; color: white; width: 30px; height: 30px; border-radius: 50%; text-align: center; line-height: 30px; margin-right: 10px;">1</span>
                            模型加载
                        </h3>
                        <ul style="font-size: 1.1em; padding-left: 40px;">
                            <li style="margin-bottom: 8px;">在左侧边栏选择模型文件(.pt)</li>
                            <li style="margin-bottom: 8px;">点击"加载模型"按钮初始化模型</li>
                            <li>支持YOLOv5/v8/v11等多种版本</li>
                        </ul>
                    </div>
                    
                    <div style="margin-bottom: 25px;">
                        <h3 style="color: #2C3E50; font-size: 1.4em;">
                            <span style="display: inline-block; background: #3498DB; color: white; width: 30px; height: 30px; border-radius: 50%; text-align: center; line-height: 30px; margin-right: 10px;">2</span>
                            图像检测
                        </h3>
                        <ul style="font-size: 1.1em; padding-left: 40px;">
                            <li style="margin-bottom: 8px;">在"图像检测"标签页上传图片</li>
                            <li style="margin-bottom: 8px;">点击"开始检测"按钮进行目标检测</li>
                            <li>支持常见图片格式(JPG/PNG等)</li>
                        </ul>
                    </div>
                    
                    <div style="margin-bottom: 25px;">
                        <h3 style="color: #2C3E50; font-size: 1.4em;">
                            <span style="display: inline-block; background: #3498DB; color: white; width: 30px; height: 30px; border-radius: 50%; text-align: center; line-height: 30px; margin-right: 10px;">3</span>
                            视频检测
                        </h3>
                        <ul style="font-size: 1.1em; padding-left: 40px;">
                            <li style="margin-bottom: 8px;">在"视频检测"标签页上传视频文件</li>
                            <li style="margin-bottom: 8px;">点击"开始生成"按钮处理视频</li>
                            <li>支持MP4/AVI/MOV等多种格式</li>
                        </ul>
                    </div>
                    
                    <div>
                        <h3 style="color: #2C3E50; font-size: 1.4em;">
                            <span style="display: inline-block; background: #3498DB; color: white; width: 30px; height: 30px; border-radius: 50%; text-align: center; line-height: 30px; margin-right: 10px;">4</span>
                            实时摄像头
                        </h3>
                        <ul style="font-size: 1.1em; padding-left: 40px;">
                            <li style="margin-bottom: 8px;">在"实时摄像头"标签页点击"启动摄像头"</li>
                            <li style="margin-bottom: 8px;">允许浏览器访问摄像头权限</li>
                            <li>点击"开始检测"进行实时目标检测</li>
                        </ul>
                    </div>
                </div>
                
                <div style="background: #F8F9FA; padding: 25px; border-radius: 15px; box-shadow: 0 6px 12px rgba(0,0,0,0.05);">
                    <h2 style="color: #3498DB; border-bottom: 3px solid #3498DB; padding-bottom: 15px; font-size: 1.8em;">⚙️ 高级功能</h2>
                    
                    <div style="margin-bottom: 25px;">
                        <h3 style="color: #2C3E50; font-size: 1.4em;">
                            <span style="display: inline-block; background: #9B59B6; color: white; width: 30px; height: 30px; border-radius: 50%; text-align: center; line-height: 30px; margin-right: 10px;">5</span>
                            标签语言
                        </h3>
                        <ul style="font-size: 1.1em; padding-left: 40px;">
                            <li style="margin-bottom: 8px;">在侧边栏选择"中文"或"English"</li>
                            <li style="margin-bottom: 8px;">选择中文时需要上传标签映射文件</li>
                            <li>格式为"类别ID 类别名称"，每行一个</li>
                        </ul>
                    </div>
                    
                    <div style="margin-bottom: 25px;">
                        <h3 style="color: #2C3E50; font-size: 1.4em;">
                            <span style="display: inline-block; background: #9B59B6; color: white; width: 30px; height: 30px; border-radius: 50%; text-align: center; line-height: 30px; margin-right: 10px;">6</span>
                            截取主要人物
                        </h3>
                        <ul style="font-size: 1.1em; padding-left: 40px;">
                            <li style="margin-bottom: 8px;">在"截取主要人物"标签页上传视频</li>
                            <li style="margin-bottom: 8px;">选择要提取的人物类别</li>
                            <li style="margin-bottom: 8px;">系统自动生成仅包含选定人物的视频</li>
                            <li>同时生成时间戳CSV文件用于音频恢复</li>
                        </ul>
                    </div>
                    
                    <div>
                        <h3 style="color: #2C3E50; font-size: 1.4em;">
                            <span style="display: inline-block; background: #9B59B6; color: white; width: 30px; height: 30px; border-radius: 50%; text-align: center; line-height: 30px; margin-right: 10px;">7</span>
                            音频恢复
                        </h3>
                        <ul style="font-size: 1.1em; padding-left: 40px;">
                            <li style="margin-bottom: 8px;">在"声音提取"标签页上传以下文件：</li>
                            <li style="margin-bottom: 8px; margin-left: 20px;">• 原始视频文件（包含音频）</li>
                            <li style="margin-bottom: 8px; margin-left: 20px;">• 提取后的视频文件（无音频）</li>
                            <li style="margin-bottom: 8px; margin-left: 20px;">• 时间戳CSV文件（由"截取主要人物"功能生成）</li>
                            <li>点击"开始恢复音频"按钮处理</li>
                        </ul>
                    </div>
                </div>
            </div>
            
            <div style="background: #EBF5FB; padding: 25px; border-radius: 15px; margin-bottom: 25px; box-shadow: 0 6px 12px rgba(0,0,0,0.05);">
                <h2 style="color: #2980B9; margin-top: 0; font-size: 1.8em; text-align: center;">❓ 常见问题解答</h2>
                
                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(350px, 1fr)); gap: 20px;">
                    <div style="background: white; padding: 20px; border-radius: 12px; box-shadow: 0 4px 8px rgba(0,0,0,0.08);">
                        <h3 style="color: #2C3E50; margin-top: 0; font-size: 1.3em;">Q: 模型加载失败怎么办？</h3>
                        <p style="color: #7F8C8D; margin: 0; font-size: 1.1em;">A: 确保model目录下有有效的.pt模型文件，检查文件路径和权限设置</p>
                    </div>
                    
                    <div style="background: white; padding: 20px; border-radius: 12px; box-shadow: 0 4px 8px rgba(0,0,0,0.08);">
                        <h3 style="color: #2C3E50; margin-top: 0; font-size: 1.3em;">Q: 中文标签不显示怎么办？</h3>
                        <p style="color: #7F8C8D; margin: 0; font-size: 1.1em;">A: 确保已上传正确的标签映射文件，格式为"0 类别名称"，并选择"中文"语言选项</p>
                    </div>
                    
                    <div style="background: white; padding: 20px; border-radius: 12px; box-shadow: 0 4px 8px rgba(0,0,0,0.08);">
                        <h3 style="color: #2C3E50; margin-top: 0; font-size: 1.3em;">Q: 视频处理速度慢怎么办？</h3>
                        <p style="color: #7F8C8D; margin: 0; font-size: 1.1em;">A: 尝试使用较小的模型、降低视频分辨率或确保系统有足够GPU资源</p>
                    </div>
                    
                    <div style="background: white; padding: 20px; border-radius: 12px; box-shadow: 0 4px 8px rgba(0,0,0,0.08);">
                        <h3 style="color: #2C3E50; margin-top: 0; font-size: 1.3em;">Q: 音频恢复失败怎么办？</h3>
                        <p style="color: #7F8C8D; margin: 0; font-size: 1.1em;">A: 确保上传的三个文件匹配，时间戳CSV文件必须由"截取主要人物"功能生成</p>
                    </div>
                    
                    <div style="background: white; padding: 20px; border-radius: 12px; box-shadow: 0 4px 8px rgba(0,0,0,0.08);">
                        <h3 style="color: #2C3E50; margin-top: 0; font-size: 1.3em;">Q: 摄像头无法启动怎么办？</h3>
                        <p style="color: #7F8C8D; margin: 0; font-size: 1.1em;">A: 检查浏览器权限设置，确保已允许访问摄像头，并确认摄像头设备正常工作</p>
                    </div>
                </div>
            </div>
            
            <div style="text-align: center; color: #7F8C8D; font-size: 1.1em; padding: 20px; background: #FDEDEC; border-radius: 12px; border-left: 5px solid #E74C3C;">
                <p style="margin: 0; font-size: 1.2em;">
                    <span style="font-size: 1.5em; margin-right: 10px;">💡</span>
                    <strong>提示:</strong> 使用前请确保已正确安装所有依赖库，并放置相应的YOLO模型文件到model目录中
                </p>
                <p style="margin: 10px 0 0 0; font-size: 1.1em;">
                    <span style="font-size: 1.3em; margin-right: 10px;">🛠️</span>
                    系统基于 Ultralytics YOLO 和 Gradio 构建
                </p>
            </div>
            """)
    
    return demo

if __name__ == "__main__":
    demo = create_interface()
    demo.launch(inbrowser=True, share=False)